// API接口基础地址
const BASE_URL = 'http://localhost:8080/api';

// 检查token是否过期
const checkTokenExpired = () => {
  const expireTime = wx.getStorageSync('tokenExpireTime');
  if (!expireTime) return true;
  return Date.now() > expireTime;
};

// 请求方法封装
const request = (url, method, data) => {
  return new Promise((resolve, reject) => {
    // 获取存储的token
    const token = wx.getStorageSync('token') || '';
    
    // 检查token是否过期
    if (token && checkTokenExpired()) {
      // token已过期，清除token并跳转到登录页
      wx.removeStorageSync('token');
      wx.removeStorageSync('tokenExpireTime');
      wx.navigateTo({
        url: '/pages/user/login?from=back',
      });
      reject('登录已过期，请重新登录');
      return;
    }
    
    wx.request({
      url: `${BASE_URL}${url}`,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // 未授权，清除token并跳转到登录页
          wx.removeStorageSync('token');
          wx.removeStorageSync('tokenExpireTime');
          wx.navigateTo({
            url: '/pages/user/login?from=back',
          });
          reject('未授权，请重新登录');
        } else {
          reject(res.data.message || '请求失败');
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

// API接口定义
const api = {
  // 用户相关
  login: (data) => request('/weChat/auth/login', 'POST', data),
  sendVerifyCode: (phone) => request('/user/sendVerifyCode', 'POST', { phone }),
  verifyPhoneLogin: (phone, verifyCode) => request('/user/phoneLogin', 'POST', { phone, verifyCode }),
  getUserInfo: () => request('/user/info', 'GET'),
  updateUserInfo: (data) => request('/user/info', 'PUT', data),
  
  // 首页相关
  getBanners: () => request('/banners', 'GET'),
  getPunchInStatus: () => request('/punch', 'GET'),
  punchIn: () => request('/points/userAddRecords', 'POST'),
  getMagazines: () => request('/weeklies', 'GET'),
  getFeaturedCourses: () => request('/lessons', 'GET'),
  getTeachers: () => request('/teachers', 'GET'),
  
  // 商城相关
  getProducts: (params) => request('/products', 'GET', params),
  getProductDetail: (id) => request(`/products/${id}`, 'GET'),
  buyProduct: (data) => request('/orders', 'POST', data),
  
  // 学院相关
  getSchools: () => request('/schools', 'GET'),
  getSchoolDetail: (id) => request(`/schools/${id}`, 'GET'),
  getSchoolCourses: (id) => request(`/schools/${id}/courses`, 'GET'),
  getSchoolRanking: (keywordOrParams, pageNum, pageSize) => {
    // 支持两种调用方式：
    // 1. getSchoolRanking(keyword, pageNum, pageSize)
    // 2. getSchoolRanking({keyword, pageNum, pageSize})
    
    if (typeof keywordOrParams === 'object') {
      const { keyword = '', pageNum = 1, pageSize = 10 } = keywordOrParams;
      return request(`/app/school/ranking?keyword=${keyword || ''}&pageNum=${pageNum || 1}&pageSize=${pageSize || 10}`, 'GET');
    } else {
      const keyword = keywordOrParams || '';
      return request(`/app/school/ranking?keyword=${keyword}&pageNum=${pageNum || 1}&pageSize=${pageSize || 10}`, 'GET');
    }
  },
  
  // 评论相关
  getStudyGardenComments: (studyGardenId, page = 1, size = 10) => 
    request(`/comments/studyGarden/${studyGardenId}?page=${page}&size=${size}`, 'GET'),
  
  getCommentReplies: (commentId, page = 1, size = 10) => 
    request(`/comments/replies/${commentId}?page=${page}&size=${size}`, 'GET'),
  
  addComment: (comment) => 
    request('/comments', 'POST', comment),
    
  likeComment: (commentId) =>
    request(`/comments/like/${commentId}`, 'POST'),
  
  // 我的相关
  getCollections: () => request('/userCollections/user', 'GET'),
  addCollection: (data) => request('/collections', 'POST', data),
  deleteCollection: (id) => request(`/collections/${id}`, 'DELETE'),
  getStudyNotes: () => request('/notes', 'GET'),
  getCertificates: () => request('/certificates', 'GET'),
  getAddresses: () => request('/addresses', 'GET'),
  addAddress: (data) => request('/addresses', 'POST', data),
  updateAddress: (id, data) => request(`/addresses/${id}`, 'PUT', data),
  deleteAddress: (id) => request(`/addresses/${id}`, 'DELETE'),

  // 地址相关
  saveAddress: (data) => request('/addresses/save','POST',data),
  // 获取树形地址结构
  treeAddress: (data) => request( '/regions/tree', 'GET',data),
  // 设置默认地址
  setDefaultAddress: (id) => request(`/addresses/${id}/default`,'POST'),

  // 周刊相关
  likeMagazine: (data) => request('/weeklies/likeWeekly','POST',data),
  // 收藏周刊
  collectMagazine: (data) => request('/userCollections','POST',data),
  // 评论周刊
  addMagazineComment: (data) => request('/comments','POST',data),
  // 获取周刊的评论
  getMagazineComments: (weeklyId, params = {}) => request(`/comments/weekly/${weeklyId}?page=${params.page || 1}&size=${params.size || 10}`,'GET'),

  // 老师相关
  getTeacherDetail: (data) => request(`/teachers/${data}`,'GET',data),
  // 点赞老师
  likeTeacher: (data) => request(`/teachers/likeTeacher`,'POST',data),
  // 获取老师的评论
  getTeacherComments: (teacherId, params = {}) => request(`/comments/teacher/${teacherId}?page=${params.page || 1}&size=${params.size || 10}`,'GET'),
  // 获取老师的回复
  getTeacherReplies: (commentId, params = {}) => request(`/comments/teacher/${commentId}?page=${params.page || 1}&size=${params.size || 10}`,'GET'),
  // 评论老师
  commentTeacher: (data) => request('/comments','POST',data),

  // 取消点赞
  cancelLikeComment: (commentId) => {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080/api/comments/DeleteLike/${commentId}`,
        method: 'POST',
        success: res => resolve(res),
        fail: err => reject(err)
      });
    });
  },
};

module.exports = {
  api,
  request,
  checkTokenExpired
}; 